package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;

import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;

/**
 * 生成查询列表的SqlStatement
 * @author guobingbing
 * @since 2023/6/12 14:48
 */
public class SelectListByFormElementGenerator extends AbstractXmlElementGenerator {

	public SelectListByFormElementGenerator(){
		super();
	}

	@Override
	public void addElements(XmlElement parentElement) {
		XmlElement answer = new XmlElement("select"); //$NON-NLS-1$
		answer.addAttribute(new Attribute(
				"id", introspectedTable.getSelectListByFormId())); //$NON-NLS-1$
		answer.addAttribute(new Attribute("resultMap", //$NON-NLS-1$
				introspectedTable.getBaseResultMapId()));

		answer.addAttribute(new Attribute("parameterType", introspectedTable.getJavaFormType())); //$NON-NLS-1$
		context.getCommentGenerator().addComment(answer);

		StringBuilder sb = new StringBuilder();
		sb.append("select "); //$NON-NLS-1$

		if (stringHasValue(introspectedTable.getSelectByPrimaryKeyQueryId())) {
			sb.append('\'');
			sb.append(introspectedTable.getSelectByPrimaryKeyQueryId());
			sb.append("' as QUERYID,"); //$NON-NLS-1$
		}
		answer.addElement(new TextElement(sb.toString()));
		answer.addElement(getBaseColumnListElement());
		if (introspectedTable.hasBLOBColumns()) {
			answer.addElement(new TextElement(",")); //$NON-NLS-1$
			answer.addElement(getBlobColumnListElement());
		}

		sb.setLength(0);
		sb.append("from "); //$NON-NLS-1$
		sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
		answer.addElement(new TextElement(sb.toString()));

		sb.setLength(0);
		sb.append("<include refid=\"queryConditions\"></include>");
		answer.addElement(new TextElement(sb.toString()));
		sb.setLength(0);
		sb.append("<include refid=\"base.orderAndPage\"></include>");
		answer.addElement(new TextElement(sb.toString()));

		if (context.getPlugins().sqlMapSelectByPrimaryKeyElementGenerated(answer, introspectedTable)) {
			parentElement.addElement(answer);
		}
	}
}
